package com.a2.appa3.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.a2.appa3.R;
import com.a2.appa3.adapter.ContactsAdapter;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.network.entity.req.Reschatlist;
import com.a2.appa3.ui.activity.FeedbackActivity;
import com.a2.appa3.ui.activity.GroundActivity;
import com.a2.appa3.ui.activity.NewfriendActivity;
import com.a2.appa3.ui.activity.NewgroundActivity;
import com.a2.appa3.ui.activity.SearchActivity;
import com.a2.appa3.util.EventBus.Newfriends;
import com.a2.appa3.util.pinyinutil;
import com.a2.appa3.widget.WaveSideBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by Administrator on 2019/6/21.
 * 通讯录
 */

public class contentFragment extends BaseFragmentSimple {
    public int REQUEST_CODE = 1006;
    @BindView(R.id.ivback)
    ImageView ivback;
    @BindView(R.id.tvback)
    TextView tvback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    @BindView(R.id.headerButtonRoot)
    LinearLayout headerButtonRoot;
    @BindView(R.id.newfriend)
    TextView newfriend;
    @BindView(R.id.rv_contacts)
    RecyclerView rvContacts;
    @BindView(R.id.side_bar)
    WaveSideBar sideBar;
    ContactsAdapter adapter;
    @BindView(R.id.newfriendnumber)
    TextView newfriendnumber;
    @BindView(R.id.newfriendlin)
    LinearLayout newfriendlin;
    @BindView(R.id.groupbt)
    LinearLayout groupbt;
    @BindView(R.id.groupnumber)
    TextView groupnumber;
    private ArrayList<Reschatlist.FriendsList> contacts = new ArrayList<>();
    private ArrayList<String> contactspinyin = new ArrayList<>();

    public static contentFragment newInstance() {
        Bundle args = new Bundle();
        contentFragment fragment = new contentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int setContentView() {
        return R.layout.contentfragment_layout;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ivback.setVisibility(View.GONE);
        tvback.setPadding(10, 0, 0, 0);
        tvback.setText("通讯录");
        headerButton.setImageResource(R.mipmap.menu_bt);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initPopuWindow1();
        initView();
        headerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popuWindow1.isShowing()) {
                    popuWindow1.dismiss();
                } else {
                    popuWindow1.showAsDropDown(headerButton, 0, 0);
                    popuWindow1.update();
                }
            }
        });
        newfriendlin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), NewfriendActivity.class));
            }
        });
        groupbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), GroundActivity.class));
            }
        });
    }

    private void initView() {
        contactspinyin.clear();
        for (int i = 'A'; i < 'Z'; i++) {
            contactspinyin.add("" + (char) i);
        }
        contactspinyin.add("Z");
        rvContacts.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ContactsAdapter(getContext(), contacts, contactspinyin, R.layout.item_contacts);
        rvContacts.setAdapter(adapter);
        sideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String index) {

                for (int i = 0; i < contacts.size(); i++) {
                    String str = contacts.get(i).nickname;
                    Boolean flag = ishanzi(str);
                    if (flag) {
                        String str1 = (String) str.subSequence(0, 1);
                        //提取汉语拼音首字母
                        String str2 = pinyinutil.getAlpha(str1);
                        if (str2.equals(index)) {
                            ((LinearLayoutManager) rvContacts.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                            return;
                        }
                    } else {
                        //英文
                        String str1 = (String) str.subSequence(0, 1);
                        if (str1.equals(index)) {
                            ((LinearLayoutManager) rvContacts.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                            return;
                        }
                    }
                }
            }
        });
    }

    PopupWindow popuWindow1 = null;

    private void initPopuWindow1() {
        try {
            View contentView1 = null;
            if (popuWindow1 == null) {
                LayoutInflater mLayoutInflater = LayoutInflater.from(getContext());
                contentView1 = mLayoutInflater.inflate(R.layout.pop_window_saoyisao, null);
                popuWindow1 = new PopupWindow(contentView1, ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
            }
            ColorDrawable cd = new ColorDrawable(0x0f000000);
            popuWindow1.setBackgroundDrawable(cd);
            popuWindow1.setOutsideTouchable(false);
            popuWindow1.setFocusable(false);
            popuWindow1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                //在dismiss中恢复透明度
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = 1f;
                    getActivity().getWindow().setAttributes(lp);
                }
            });

            TextView instancorder = contentView1.findViewById(R.id.instancorder);
            TextView todayover = contentView1.findViewById(R.id.todayover);
            TextView addorder = contentView1.findViewById(R.id.addorder);
            TextView newgroundbt = contentView1.findViewById(R.id.newgroundbt);
            RelativeLayout content = contentView1.findViewById(R.id.content);
            instancorder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popuWindow1.dismiss();
                    startActivity(new Intent(getContext(), NewfriendActivity.class));
                }
            });
            final PopupWindow finalPopuWindow = popuWindow1;
            todayover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //https://github.com/yipianfengye/android-zxingLibrary
                    popuWindow1.dismiss();
                    Intent intent = new Intent(getContext(), CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            });
            newgroundbt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getContext(), "创建群聊", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getContext(), NewgroundActivity.class));
                }
            });
            addorder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popuWindow1.dismiss();
                    startActivity(new Intent(getContext(), FeedbackActivity.class));

                }
            });
            content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popuWindow1.dismiss();
                }
            });
        } catch (Exception e) {
        }

    }

    Boolean ishanzi(String characters) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < characters.length(); i++) {

            char ch = characters.charAt(i);
            if ((ch >> 7) == 0) {
                // 不是汉字
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private void initData() {
        contacts.clear();
        contacts.addAll(Info.friendlist);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (!TextUtils.isEmpty(result)) {
                        Intent intent = new Intent(getContext(), SearchActivity.class);
                        intent.putExtra("username", result + "");
                        intent.putExtra("usertype", "users");
                        startActivity(intent);
                    } else {
                        Toast.makeText(getContext(), "抱歉哦未检测到二维码中的信息:" + result, Toast.LENGTH_LONG).show();
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Newfriends messageEvent) {
        newfriendnumber.setText(messageEvent.getMessage());
        initData();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Info.roomList != null) {
            groupnumber.setText(Info.roomList.size() + "");
        }
//        if (Info.Token == null) {
//            startActivity(new Intent(getContext(), LoginActivity.class));
//        }
    }
}


